<template>
  <div class="login" ref="login">
    <div class="container">
      <v-header></v-header>
      <div class="content">
        <div class="title">
          <div class="title-item" :class="{'active-item': loginOrRegister === 'login'}" @click="handleLoginItem">
            <span>登錄</span>
          </div>
          <div class="title-item" :class="{'active-item': loginOrRegister === 'register'}" @click="handleRegisterItem">
            <span>註冊</span>
          </div>
        </div>
        <div class="login-container" v-show="loginOrRegister === 'login'">
          <el-form :model="loginForm" :rules="loginRules" ref="loginForm" class="login-form">
              <el-form-item prop="email">
                <el-input type="text" placeholder="請輸入手機號碼" v-model="loginForm.email" auto-complete="off"></el-input>
              </el-form-item>
              <el-form-item prop="pwd">
                <el-input type="password" placeholder="輸入登錄密碼" v-model="loginForm.pwd" auto-complete="off"></el-input>
              </el-form-item>
              <imgcode-form-item :form="loginForm" :imgBase="imgBase" @handleImgcode="changeImgcode('loginForm')"></imgcode-form-item>
            </el-form>
            <p class="forget-password" @click="handleForget">忘記密碼？</p>
            <el-button class="submit-btn" type="primary" @click="handleLogin('loginForm')">登  錄</el-button>
            <p class="tip-description">還沒有CHAOEX賬號？<span @click="handleRegisterItem">點我註冊</span></p>
        </div>
        <div class="register-container" v-show="loginOrRegister === 'register'">
          <el-form :model="registerForm" :rules="registerRules" ref="registerForm">
              <email-input-form-item :form="registerForm"></email-input-form-item>
            <el-form-item prop="pwd">
              <el-input type="password" placeholder="設置賬號登錄密碼" v-model="registerForm.pwd" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item prop="checkPass">
              <el-input type="password" placeholder="確認賬號登錄密碼" v-model="registerForm.checkPass" auto-complete="off"></el-input>
            </el-form-item>
            <imgcode-form-item :form="registerForm" :imgBase="imgBase" @handleImgcode="changeImgcode('registerForm')"></imgcode-form-item>
            <vercode-input-form-item :form="registerForm" :showTime="showTime" :timeCount="timeCount" @handleVercode="changeVercode"></vercode-input-form-item>
          </el-form>
          <el-button type="primary" class="submit-btn" @click="handleRegister('registerForm')">註  冊</el-button>
          <p class="tip-description">已有賬號，<span @click="handleLoginItem">去登錄</span></p>
        </div>
      </div>
    </div>
    <transition name="fade">
      <div class="google-dialog" v-show="googleDialog">
        <div class="google-container">
          <span class="google-dialog-close" @click="googleDialogClose"></span>
          <div class="google-input-wrap">
            <el-form :model="googleForm" ref="googleForm">
              <el-form-item class="google-form-item" prop="clientPassword"
                :rules="[
                  { required: true, message: '請輸入谷歌驗證碼'},
                  { max:6, message: '驗證碼錯誤'}
                ]"
              >
                <el-input class="google-input" type="password" placeholder="谷歌驗證碼" v-model="googleForm.clientPassword" auto-complete="off">
                  <template slot="prepend">
                    <div class="prefix-img"></div>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-button class="google-btn" @click="handleGoogle('googleForm')" type="primary">確認提交</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </transition>
  </div>
</template>

<script>
import Header from '@/components/Header'
import EmailInputFormItem from '@/components/EmailInputFormItem'
import ImgcodeFormItem from '@/components/ImgcodeFormItem'
import VercodeInputFormItem from '@/components/VercodeInputFormItem'
import getLocationQuery from '@/utils/getLocationQuery'
import { getVercodeImg, login, googleAuth, queryPhone, sendEmailForRegister, register } from '@/Api/request'
import MD5 from '@/utils/md5'
import { mapMutations } from 'vuex'
export default {
  name: 'login',
  data () {
    const validateEmail = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('請輸入手機號碼'))
      } else {
        if (/^[1][3,4,5,7,8][0-9]{9}$/.test(value)) {
          const queryPhoneJson = {
            phone: this.registerForm.email
          }
          queryPhone(queryPhoneJson).then(res => {
            console.log(res)
            if (res.status === 600) {
              callback(new Error('手機號已註冊'))
            }
            if (res.status === 200) {
              callback()
            }
          })
        } else {
          callback(new Error('手機號格式錯誤'))
        }
      }
    }
    const validateImgcode = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('請輸入圖片驗證碼'))
      } else {
        callback()
      }
    }

    const validateCheckPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('請輸入確認密碼'))
      } else {
        if (this.registerForm.checkPass !== this.registerForm.pwd) {
          callback(new Error('兩次密碼輸入不一致'))
        }
        callback()
      }
    }

    return {
      showTime: false,
      timeCount: 60,
      googleDialog: false,
      loginOrRegister: 'login',
      imgBase: '',
      codeid: '',
      loginForm: {
        email: ''.trim(),
        pwd: '',
        imgcode: ''
      },
      loginRules: {
        email: [
          { required: true, message: '請輸入手機號碼', trigger: 'blur' },
          { max: 50, message: '最大可輸入長度50', trigger: 'blur' },
          { pattern: /^[1][3,4,5,7,8][0-9]{9}$|^(\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$).{0,50}$/, message: '手機號或郵箱號格式錯誤', trigger: 'blur' }
        ],
        pwd: [
          { required: true, message: '請輸入登錄密碼', trigger: 'blur' }
        ],
        imgcode: [
          { required: true, message: '請輸入圖片驗證碼', trigger: 'blur' }
        ]
      },
      registerForm: {
        email: ''.trim(),
        pwd: '',
        checkPass: '',
        imgcode: '',
        vercode: ''
      },
      registerRules: {
        email: [
          { validator: validateEmail, trigger: 'blur' }
        ],
        pwd: [
          { required: true, message: '請輸入登錄密碼', trigger: 'blur' },
          { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,16}$/, message: '密碼至少由大寫字母+小寫字母+數字，8-16位組成', trigger: 'blur' }
        ],
        checkPass: [
          { validator: validateCheckPass, trigger: 'blur' }
        ],
        imgcode: [
          { validator: validateImgcode, trigger: 'blur' }
        ],
        vercode: [
          { required: true, message: '請輸入驗證碼', trigger: 'blur' }
        ]
      },
      googleForm: {
        clientPassword: ''
      }
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.changeImgcode()
      this._initScroll()
    })
  },
  methods: {
    ...mapMutations([
      'SET_TOKEN_UID'
    ]),
    _initScroll () {
      this.loginScroll = new this.$BScroll(this.$refs.login, {
        click: true,
        probeType: 3,
        autoBlur: false
      })
    },
    changeImgcode () {
      this.loginForm.imgcode = ''
      this.registerForm.imgcode = ''
      getVercodeImg().then(res => {
        console.log(res)
        if (res.status === 200) {
          this.imgBase = 'data:image/png;base64,' + res.attachment.IMGCode
          this.codeid = res.attachment.codeUUID
        }
      })
    },
    changeVercode () {
      if (this.registerForm.email === '') {
        this.$message({
          message: '請輸入手機號碼',
          center: true,
          type: 'error'
        })
        return
      }
      const dataJson = {
        email: this.registerForm.email,
        imgcode: this.registerForm.imgcode,
        codeid: this.codeid
      }
      sendEmailForRegister(dataJson).then(res => {
        if (this.showTime) { return }
        if (res.status !== 200) {
          this.$message({
            message: res.message,
            center: true,
            type: 'error'
          })
          this.changeImgcode()
          this.registerForm.imgcode = ''
        } else {
          this.$message({
            message: '發送短訊成功',
            center: true,
            type: 'success'
          })
          this.registerForm.vercode = ''
          this.showTime = true
          const _this = this
          this.timeCount = 59
          clearInterval(this.timer)
          this.timer = setInterval(function () {
            _this.timeCount--
            if (_this.timeCount === 0) {
              _this.showTime = false
              _this.timeCount = 60
              clearInterval(_this.timer)
            }
          }, 1000)
        }
      })
    },
    handleRegisterItem () {
      this.loginOrRegister = 'register'
      this.$refs.loginForm.resetFields()
      this.changeImgcode()
    },
    handleLoginItem () {
      this.loginOrRegister = 'login'
      this.$refs.registerForm.resetFields()
      this.changeImgcode()
    },
    handleLogin (formName) {
      this.$refs[formName].validate((valid, detail) => {
        if (valid) {
          const dataJson = {
            email: this.loginForm.email,
            pwd: MD5(this.loginForm.pwd),
            vercode: this.loginForm.imgcode,
            codeid: this.codeid,
            source: '1'
          }
          login(dataJson).then(res => {
            this.changeImgcode()
            this.loginForm.imgcode = ''
            if (res.status === 200) {
              const data = {
                uid: res.attachment.uid,
                token: res.attachment.token,
                loginEmail: this.loginForm.email
              }
              this.SET_TOKEN_UID(data)
              this.$router.push({
                name: 'personal'
              })
            } else if (res.status === 5555) {
              this.googleDialog = true
            } else {
              this.$message({
                message: res.message,
                center: true,
                type: 'error'
              })
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleGoogle (formName) {
      this.$refs[formName].validate((valid, detail) => {
        if (valid) {
          const dataJson = {
            email: this.loginForm.email,
            clientPassword: this.googleForm.clientPassword,
            source: 1
          }
          this.$refs[formName].resetFields()
          googleAuth(dataJson).then(res => {
            this.changeImgcode()
            this.loginForm.imgcode = ''
            if (res.status === 200) {
              const data = {
                token: res.attachment.token,
                uid: res.attachment.uid
              }
              this.SET_TOKEN_UID(data)
              this.$router.push({
                name: 'personal'
              })
            } else {
              this.$message({
                message: res.message,
                center: true,
                type: 'error'
              })
            }
          })
        } else {
          console.log('err submit!')
        }
      })
    },
    handleForget () {
      this.$router.push({
        name: 'forget'
      })
    },
    handleRegister (formName) {
      console.log(getLocationQuery().invitedId)
      this.$refs[formName].validate((valid, detail) => {
        if (valid) {
          const dataJson = Object.assign({}, this.registerForm, {
            codeid: this.codeid,
            inviteId: getLocationQuery().invitedId || ''
          })
          delete dataJson.checkPass
          this.$refs[formName].resetFields()
          register(dataJson).then(res => {
            if (res.status === 200) {
              this.$message({
                message: '註冊成功，請登錄',
                center: true,
                type: 'success'
              })
              this.registerForm.imgcode = ''
              this.registerForm.vercode = ''
              this.changeImgcode()
            } else {
              this.registerForm.imgcode = ''
              this.changeImgcode()
              this.$message({
                message: res.message,
                center: true,
                type: 'error'
              })
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    googleDialogClose () {
      this.$refs.googleForm.resetFields()
      this.googleDialog = false
      this.changeImgcode()
      this.loginForm.imgcode = ''
    }
  },
  components: {
    'vHeader': Header,
    ImgcodeFormItem,
    VercodeInputFormItem,
    EmailInputFormItem
  }
}
</script>

<style lang="stylus" rel="stylesheet/stylus">
.login-form, .register-form{
  position: relative;
}
.el-form-item__error{
  font-size: 28px;
  line-height: 28px;
}
.el-form, .el-form-item{
  margin-bottom: 30px;
}
.el-input__inner{
  height: 91px;
  line-height: 91px;
  padding: 0 26px;
  background:rgba(255,255,255,0.3);
  border-radius:46px;
  border: none;
  outline: none;
  font-size: 34px;
  color:rgba(206,166,207,1);
}
.google-input{
  height: 84px;
  border-radius: 42px;
  border: 1px solid rgba(140,140,140,1); /*no*/
  .el-input-group__prepend{
    padding: 24px 20px;
    background: #fff;
    border: none;
    border-top-left-radius: 42px;
    border-bottom-left-radius: 42px;
    &:after{
      position: absolute;
      right: 0;
      top: 23px;
      height: 46px;
      content: '';
    }
  }
  .prefix-img{
    position: relative;
    width: 55px;
    height: 36px;
    background: url("../assets/images/google.png") no-repeat;
    &:after{
      content: "";
      position: absolute;
      right: -20px;
      top: 0;
      height: 100%;
      width: 0;
      border-right: 1px solid rgba(140,140,140,1); /*no*/
    }
  }
}

@media (-webkit-min-device-pixel-ratio: 2),(min-device-pixel-ratio: 2)
  .google-input .prefix-img
    background-image: url("../assets/images/google@2x.png");
    background-size: cover;

@media (-webkit-min-device-pixel-ratio: 3),(min-device-pixel-ratio: 3)
  .google-input .prefix-img
    background-image: url("../assets/images/google@3x.png");
    background-size: cover;
  .el-input__inner{
    font-size: 36px;
  }
</style>

<style scoped lang="stylus" rel="stylesheet/stylus">
.login{
  position: relative;
}
.container{
  padding: 37px 49px 57px;
}
.header{
  margin-bottom: 76px;
}

.title{
  display: flex;
  margin-bottom: 36px;
  .title-item{
    flex: 1;
    span{
      display: block;
      width: 70px;
      height: 32px;
      margin: 0 auto;
      padding-bottom: 12px;
      font-size: 32px;
      font-weight: 600;
      color: rgba(255,255,255,1);
      line-height: 32px;
      text-align: center;
    }
    &.active-item{
      span{
        border-bottom: 7px solid #fff;
      }
    }
  }
}

.forget-password{
  margin-bottom: 230px;
  font-size: 26px;
  color:rgba(206,166,207,1);
  line-height:36px;
  text-align: right;
}
.submit-btn{
  width: 100%;
  height: 91px;
  margin-bottom: 36px;
  border-radius: 46px;
  font-size: 36px;
  border: none;
  outline: none;
  background: linear-gradient(to right, #1293FF, #6FBDFF);
  box-shadow: 0px 0px 4px 4px rgba(24,150,255,0.58)
}
.tip-description{
  font-size:26px;
  color:#CEA6CF;
  line-height: 26px;
  text-align: center;
  span{
    color: rgba(255, 255, 255, 1);
  }
}

.register-container .el-form{
  margin-bottom: 56px;
}

.google-dialog{
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.6);
  &.fade-enter-active, &.fade-leave-active{
    transition: all 0.3s;
  }
  &.fade-enter, &.fade-leave-to{
    opacity: 0;
  }
  .google-container{
    position: absolute;
    left: 62px;
    top: 289px;
    box-sizing: border-box;
    width: 620px;
    height: 455px;
    padding: 110px 72px 53px;
    background: #fff;
    .google-form-item{
      margin-bottom: 117px;
    }
    .google-btn{
      width: 100%;
      height: 91px;
      border-radius:46px;
      font-size:36px;
      border: none;
      background: linear-gradient(to right, #1293FF, #6FBDFF);
      box-shadow: 0px 0px 4px 4px rgba(24,150,255,0.58);
    }
  }
}

.google-dialog-close{
  position: absolute;
  top: -68px;
  right: 0;
  width: 41px;
  height: 41px;
  background: url("../assets/images/remove.png") no-repeat;
  backkground-size: cover;
  border-radius: 50%;
  &:after{
    content: "";
    position: absolute;
    left: 18px;
    bottom: -27px;
    width: 4px;
    height: 27px;
    background: #fff;
  }
}

@media (-webkit-min-device-pixel-ratio: 2),(min-device-pixel-ratio: 2)
  .google-dialog-close
    background-image: url("../assets/images/remove@2x.png");
    background-size: cover;

@media (-webkit-min-device-pixel-ratio: 3),(min-device-pixel-ratio: 3)
  .google-dialog-close
    background-image: url("../assets/images/remove@3x.png");
    background-size: cover;
</style>
